package com.letv.core.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.letv.core.bean.DownloadLocalVideoItemBean;
import com.letv.core.db.PreferencesManager;
import com.media.NativeThumbnail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * 文件工具类
 * 
 * @author zhuqiao
 * 
 */
public class FileUtils {
    /**
     * 缓存根目录
     */
    public static final String ROOT_FOLDER = "Letv/";

    /**
     * 图片缓存目录
     */
    public static final String IMAGE_CACHE_FOLDER = ROOT_FOLDER + "cache/pics/";
    private static final String IMAGE_CACHE_FOLDER_SMALL = "letv/cache/pics/";// 容错

    private static final String DATA_INFO_FOLDER = ROOT_FOLDER + "storage/" + "relevant_data/";

    /**
     * 获取sd卡路径
     * 
     * @param context
     * @return
     */
    public static String getSDCardPath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return Environment.getExternalStorageDirectory().getPath() + File.separator + ROOT_FOLDER;
        }

        return null;
    }

    /**
     * 获取缓存文件路径(系统)
     * 
     * @param context
     * @return
     */
    public static String getSysCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        }
        return context.getCacheDir().getPath();
    }

    /**
     * 获取图片缓存路径
     * 
     * @param context
     * @return
     */
    public static String getBitmapCachePath(Context context) {
        File dir = new File(Environment.getExternalStorageDirectory(), IMAGE_CACHE_FOLDER);
        if (!dir.exists()) {
            boolean result = dir.mkdirs();
            if (result) {
                LogInfo.log("zhuqiao", "文件夹创建成功");
            } else {
                LogInfo.log("zhuqiao", "文件夹创建失败，改小写");
                dir = new File(Environment.getExternalStorageDirectory(), IMAGE_CACHE_FOLDER_SMALL);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            }
        }

        return dir.getAbsolutePath();
    }

    // ============================== 普通文件存储 ==============================
    public static String getRelevantData(Context context, String filename) {
        File file = getRelevantFile(context, filename);

        if (file != null) {
            ObjectInputStream in = null;

            try {
                in = new ObjectInputStream(new FileInputStream(file));
                return (String) in.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void saveRelevantData(Context context, String filename, String data) {
        File file = getRelevantFile(context, filename);

        if (file != null && !TextUtils.isEmpty(data)) {
            ObjectOutputStream out = null;
            try {
                out = new ObjectOutputStream(new FileOutputStream(file));
                out.writeObject(data);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static File getRelevantFile(Context context, String filename) {
        String path = getSDCardPath(context);
        if (TextUtils.isEmpty(path)) {
            return null;
        }

        try {
            File dir = new File(Environment.getExternalStorageDirectory(), DATA_INFO_FOLDER);
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }

            File file = new File(dir, filename);

            if (!file.exists()) {
                file.createNewFile();
            }

            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // ============================== 普通文件存储 end ==============================

    // ============================== 服务器相关 ==============================

    /**
     * 保存服务器数据缓存
     *
     * @param context
     * @param cacheName 缓存文件名
     * @param data 保存的数据
     */
    public static boolean saveApiFileCache(Context context, String cacheName, String data) {
        if (context == null || TextUtils.isEmpty(cacheName)) {
            return false;
        }

        BaseTypeUtils.ensureStringValidate(data);

        FileOutputStream fos = null;
        try {
            fos = context.openFileOutput(cacheName, Context.MODE_PRIVATE);
            fos.write(data.getBytes());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

    /**
     * 获取服务器数据缓存
     *
     * @param context
     * @param cacheName 缓存文件名
     * @return
     */
    public static String getApiFileCache(Context context, String cacheName) {
        if (context == null || TextUtils.isEmpty(cacheName)) {
            return null;
        }

        FileInputStream fis = null;
        try {
            fis = context.openFileInput(cacheName);
            if (fis == null) {
                return null;
            }

            // 文件长度
            int length = fis.available();
            byte[] buffer = new byte[length];
            fis.read(buffer);
            return new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    /**
     * 清除服务器数据缓存文件
     *
     * @param context
     * @param cacheName 缓存文件名
     */
    public static void deleteApiFileCache(Context context, String cacheName) {
        if (context == null || TextUtils.isEmpty(cacheName)) {
            return;
        }

        context.deleteFile(cacheName);
    }

    /**
     * 清除所有服务器数据缓存文件
     *
     * @param context
     */
    public static void deleteAllApiFileCache(Context context) {
        if (context == null) {
            return;
        }

        String[] fileNames = context.fileList();
        if (BaseTypeUtils.isArrayEmpty(fileNames)) {
            return;
        }

        synchronized (fileNames) {
            for (String cacheName : fileNames) {
                context.deleteFile(cacheName);
            }
        }
    }

    // ============================== 服务器相关 end ==============================
    /**
     * 返回当前下载路径
     * 
     * @return
     */
    public File getDownloadDir() {
        File downloadDir = new File(PreferencesManager.getInstance().getDownloadLocation());

        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }
        return downloadDir;
    }

    // ================================本地视频 start sumin.zhao ============================

    /**
     * 通过File对象获得LocalVideoItem对象
     * 
     * @param file
     * @return
     */
    public static DownloadLocalVideoItemBean fileToLocalVideoItem(File file) {
        DownloadLocalVideoItemBean item = new DownloadLocalVideoItemBean();
        NativeThumbnail retriever = new NativeThumbnail(file.getAbsolutePath());

        item.setFileDate(file.lastModified());
        item.setFileDuration(retriever.getDuration());
        item.setFileSize(file.length());
        item.setPath(file.getAbsolutePath());
        item.setPosition(-1000);
        item.setTitle(pathToTitle(file));
        item.setVideo_W_H(retriever.getResolution());
        item.setVideoType(fileToType(file));
        return item;
    }

    /**
     * 通过File对象获得LocalVideoItem对象
     * 
     * @param file
     * @return
     */
    public static DownloadLocalVideoItemBean fileToLocalVideoItemBySystem(File file) {
        DownloadLocalVideoItemBean item = new DownloadLocalVideoItemBean();

        LetvMediaMetadataRetriever retriever = new LetvMediaMetadataRetriever();
        retriever.setDataSource(file.getAbsolutePath());
        item.setFileDate(file.lastModified());
        item.setFileDuration(retriever.getFileDuration());
        item.setFileSize(file.length());
        item.setPath(file.getAbsolutePath());
        item.setPosition(-1000);
        item.setTitle(pathToTitle(file));
        item.setVideo_W_H(retriever.getVideo_W_H());
        item.setVideoType(fileToType(file));

        return item;
    }

    public static String fileToType(File file) {
        String path = file.getAbsolutePath();
        String type = null;
        if (path.lastIndexOf('.') != -1) {
            type = path.substring(path.lastIndexOf('.'), path.length());
        }

        if (null == type) {
            return "";
        } else {
            return type.replace(".", "").toLowerCase();
        }

        // return null == type ? "" : type;
    }

    /**
     * 将fileName转换成VideoTitle
     */
    public static String pathToTitle(File file) {
        if (null != file) {
            return pathToTitle(file.getName());
        } else {
            return "";
        }
    }

    /**
     * 将fileName转换成VideoTitle
     */
    public static String pathToTitle(String fileName) {
        String tmp = null;
        if (null != fileName && !"".equals(fileName)) {
            int index = fileName.lastIndexOf(".");
            tmp = fileName.substring(0, index);
        } else {
            tmp = "";
        }
        LogInfo.log("pathToTitle", "pathToTitle = " + tmp);
        return tmp;
    }

    /**
     * 判断FileList中的文件是否存在
     */
    public static void checkFileIsEnabledPath(ArrayList<DownloadLocalVideoItemBean> listFiles) {

        for (int i = 0; i < listFiles.size(); i++) {

            if (!checkFileIsEnabledPath(listFiles.get(i).getPath())) {
                listFiles.remove(i);
                i--;
            }
        }

    }

    /**
     * 判断path是否存在
     * 
     * @param path
     * @return
     */
    public static boolean checkFileIsEnabledPath(String path) {
        if (null != path && !"".equals(path)) {
            File file = new File(path);
            return checkFileIsEnabledPath(file);

        } else {
            return false;
        }

    }

    /**
     * 判断file是否存在
     * 
     * @param file
     * @return
     */
    public static boolean checkFileIsEnabledPath(File file) {
        return null != file && file.exists();
    }

    /**
     * 得到日期
     * 
     * @param time
     * @return
     * */
    public String timeToString(long time) {

        // 按自定义格式SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = new Date(time);
        return formatTime.format(currentTime);
    }

    /**
     * 得到MB数显示
     * 
     * @param bytesize
     * @return
     */
    public static String longToMbString(long bytesize) {

        DecimalFormat df = new DecimalFormat("0.##");
        Double btypesizedouble = new Double(bytesize);
        Double sizefloat = 0.00d;
        String suffix = "";
        if (bytesize == 0) {

            sizefloat = 0d;
            suffix = "MB";
        } else if (bytesize < 1024) {

            sizefloat = btypesizedouble;
            suffix = "bytes";
        } else if (bytesize >= 1024 && bytesize < 1024 * 1024) {

            sizefloat = btypesizedouble / 1024;
            suffix = "KB";
        } else if (bytesize >= 1024 * 1024 && bytesize < 1024 * 1024 * 1024) {

            sizefloat = btypesizedouble / 1024 / 1024;
            suffix = "MB";
        } else if (bytesize >= 1024 * 1024 * 1024) {

            sizefloat = btypesizedouble / 1024 / 1024 / 1024;
            suffix = "GB";
        }

        return df.format(sizefloat) + suffix;
    }

    // ================================本地视频 end sumin.zhao ============================

    /**
     * 根据图片本地路径获得图片bitmap
     * 
     * @param path
     * @param screenWidth
     * @param screenHeight
     * @return
     * @throws FileNotFoundException
     */
    public static Bitmap getBitmapByPath(String path, int screenWidth, int screenHeight) throws FileNotFoundException {
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        FileInputStream in = null;
        in = new FileInputStream(file);
        if (options != null) {
            Rect r = new Rect(0, 0, screenWidth, screenHeight);
            int w = r.width();
            int h = r.height();
            int maxSize = w > h ? w : h;
            int inSimpleSize = computeSampleSize(options, maxSize, w * h);
            options.inSampleSize = inSimpleSize;
            options.inJustDecodeBounds = false;
        }
        Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return bitmap;
    }

    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int UNCONSTRAINED = -1;
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength),
                Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == UNCONSTRAINED) && (minSideLength == UNCONSTRAINED)) {
            return 1;
        } else if (minSideLength == UNCONSTRAINED) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 删除文件(异步)
     * 
     * @param file
     */
    public static void deleteFile(final File file) {

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                LogInfo.log("deleteFile", "deleteFile doInBackground file.exists() :  " + file.exists());
                if (file.exists()) {
                    file.delete();
                }
                return null;
            }
        }.execute();
    }

    public static void copyBigDataToSD(Context context, String strOutFileName) {
        try {
            InputStream myInput;
            LogInfo.log("LM", "strOutFileName  " + strOutFileName);
            File file = new File(strOutFileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            File files = new File(strOutFileName + "/letv_icon.png");
            files.createNewFile();
            OutputStream myOutput = new FileOutputStream(files.getAbsolutePath());
            myInput = context.getResources().getAssets().open("letv_icon.png");
            byte[] buffer = new byte[1024];
            int length = myInput.read(buffer);
            while (length > 0) {
                myOutput.write(buffer, 0, length);
                length = myInput.read(buffer);
            }
            myOutput.flush();
            myInput.close();
            myOutput.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
